/**
 * Created by Ysssssss on 2021/4/30.
 */

import React, { PureComponent } from 'react'
import PageBackHeader from "@common/PageBackHeader";
import PageSubNav from "@common/PageSubNav";
import { withRouter } from "react-router-dom";

import { Button, Modal, Row, Col, Radio } from "antd";
import {getHistoryMatchParams} from "@utils/setUrlQuery";
import {PLATFORM_KEY, PLATFORM_TEMPLATE_LIST} from "@constants/PlatformList";
import {connect} from "react-redux";
import {
    getShoppingMallDesignInfo,
    editShoppingMallDesignInfo
} from "@sagas/shoppingMall/shoppingMallSettings";
import {getBilinInfo} from "@utils/localStorage";
import {TEMPLATE_MODULE_NAME} from "@constants/ShoppingMallDesign";
import notify from "@utils/tip";
import {arrayToObject} from "@utils/arrayHelper";
import _ from 'lodash'

export const DesignTemplateContext = React.createContext({});


const getUniqueIdFunc = () => {
    let id = 0
    return () => id ++
}

@connect(({ user }) => ({
    userInfoInStore: user.userInfoInStore
}), {
    getShoppingMallDesignInfo,
    editShoppingMallDesignInfo
})
@withRouter
class ShoppingMallDesignDetailPage extends PureComponent {
    constructor(props) {
        super(props);
        this.getHomeUniqueId = getUniqueIdFunc()
        this.state = {
            decorationInfo: null,
            isEdited: false,
            copyPlatformId: ''
        }
    }

    componentDidMount () {
        this.getDesignInfo()
    }

    getDesignInfo () {
        const { platformId } = getHistoryMatchParams(this.props)
        this.props.getShoppingMallDesignInfo({
            sourceType: platformId
        }, res => {
            let templateDecorationInfo = res.decoration_info
            this.reformDesignInfo(templateDecorationInfo, res.prods)
        })
    }

    reformDesignInfo (templateDecorationInfo = {}, prods = []) {
        const prodsMap = arrayToObject(prods, 'id')
        let decorationInfo = {}
        for(let key in templateDecorationInfo) {
            const module = {
                ...templateDecorationInfo[key]
            }
            switch (key) {
                case 'home':
                    let homeContent = module.content.map(item => {
                        switch (item.moduleName) {
                            case 'banner':
                                let bannerList = item.bannerList.map(banner => {
                                    let goods = [];
                                    banner.goodsIds.forEach(id => prodsMap[id] && goods.push(prodsMap[id]))
                                    return {
                                        ...banner,
                                        goods
                                    }
                                })
                                return {
                                    ...item,
                                    bannerList,
                                    uniqueId: this.getHomeUniqueId()
                                }
                            case 'feature':
                                let menuList = item.menuList.map(menu => {
                                    let goods = [];
                                    menu.goodsIds.forEach(id => prodsMap[id] && goods.push(prodsMap[id]))
                                    return {
                                        ...menu,
                                        goods
                                    }
                                })
                                return {
                                    ...item,
                                    menuList,
                                    uniqueId: this.getHomeUniqueId()
                                }
                            case 'column-content':
                                let goods = [];
                                item.goodsIds.forEach(id => prodsMap[id] && goods.push(prodsMap[id]))
                                return {
                                    ...item,
                                    goods,
                                    uniqueId: this.getHomeUniqueId()
                                }
                            default:
                                return {
                                    ...item,
                                    uniqueId: this.getHomeUniqueId()
                                }
                        }
                    })
                    decorationInfo.home = {
                        ...module,
                        content: homeContent
                    }
                    break;
                case 'special':
                    let specialContent = module.content.map(item => {
                        switch(item.moduleName) {
                            case "banner":
                                let bannerList = item.bannerList.map(banner => {
                                    let goods = [];
                                    banner.goodsIds.forEach(id => prodsMap[id] && goods.push(prodsMap[id]))
                                    return {
                                        ...banner,
                                        goods
                                    }
                                })
                                return {
                                    ...item,
                                    bannerList
                                }
                            default:
                                return item
                        }
                    })
                    decorationInfo.special = {
                        ...module,
                        content: specialContent
                    }
                    break;
                case 'cart':
                    let goods = [];
                    module.goodsIds.forEach(id => prodsMap[id] && goods.push(prodsMap[id]))
                    decorationInfo.cart = {
                        ...module,
                        goods
                    }
                    break
                default:
                    decorationInfo[key] = {
                        ...module,
                    }
                    break;
            }
        }
        this.setState({
            decorationInfo
        })
    }

    handleDesignInfoChange (key, value) {
        const { decorationInfo } = this.state
        this.setState({
            decorationInfo: {
                ...decorationInfo,
                [key]: value
            },
            isEdited: true
        })
    }

    handleSubmit (callback) {
        const { decorationInfo: stateDecorationInfo } = this.state
        const { platformId } = getHistoryMatchParams(this.props)
        let prodIds = []
        let decorationInfo = {}
        for(let key in stateDecorationInfo) {
            const module = _.cloneDeep(stateDecorationInfo[key])

            switch (key) {
                case 'home':
                    let homeContent = module.content.map(item => {
                        switch (item.moduleName) {
                            case 'banner':
                                let bannerList = item.bannerList.map(banner => {
                                    let goodsIds = banner.goods.map(good => good.id)
                                    prodIds = prodIds.concat(goodsIds)
                                    delete banner.goods
                                    return {
                                        ...banner,
                                        goodsIds
                                    }
                                })
                                return {
                                    ...item,
                                    bannerList
                                }
                            case 'feature':
                                let menuList = item.menuList.map(menu => {
                                    let goodsIds = menu.goods.map(good => good.id)
                                    prodIds = prodIds.concat(goodsIds)
                                    delete menu.goods
                                    return {
                                        ...menu,
                                        goodsIds
                                    }
                                })
                                return {
                                    ...item,
                                    menuList
                                }
                            case 'column-content':
                                let goodsIds = item.goods.map(good => good.id)
                                prodIds = prodIds.concat(goodsIds)
                                delete item.goods
                                return {
                                    ...item,
                                    goodsIds
                                }
                            default:
                                return item
                        }
                    })
                    decorationInfo.home = {
                        ...module,
                        content: homeContent
                    }
                    break;
                case 'special':
                    let specialContent = module.content.map(item => {
                        switch(item.moduleName) {
                            case "banner":
                                let bannerList = item.bannerList.map(banner => {
                                    let goodsIds = banner.goods.map(good => good.id)
                                    prodIds = prodIds.concat(goodsIds)
                                    delete banner.goods
                                    return {
                                        ...banner,
                                        goodsIds
                                    }
                                })
                                return {
                                    ...item,
                                    bannerList
                                }
                            default:
                                return item
                        }
                    })
                    decorationInfo.special = {
                        ...module,
                        content: specialContent
                    }
                    break;
                case 'cart':
                    let goodsIds = module.goods.map(good => good.id)
                    prodIds = prodIds.concat(goodsIds)
                    delete module.goods
                    decorationInfo.cart = {
                        ...module,
                        goodsIds
                    }
                    break
                default:
                    decorationInfo[key] = {
                        ...module
                    }
                    break;
            }
        }
        this.props.editShoppingMallDesignInfo({
            sourceType: platformId,
            decorationInfo,
            prodIds: Array.from(new Set(prodIds))
        }, () => {
            this.setState({
                isEdited: false
            })
            notify('保存成功', 'success')
            typeof callback === 'function' && callback()
        })
    }

    beforeGoBack (callback) {
        const { isEdited } = this.state
        if (isEdited) {
            Modal.confirm({
                title: '是否保存当前设置',
                onOk: this.handleSubmit.bind(this, callback),
                onCancel: callback
            })
        } else {
            callback()
        }
    }

    copyTemplate () {
        const { platformId } = getHistoryMatchParams(this.props)
        const { copyPlatformId } = this.state
        const handleTemplateChange = e => {
            this.setState({
                copyPlatformId: e.target.value
            })
        }
        Modal.confirm({
            title: '复制后当前模版全部页面将被替换',
            content: (
                <Row>
                    <Col span={6}>选择模版</Col>
                    <Col span={18}>
                        <Radio.Group defaultValue={copyPlatformId} onChange={handleTemplateChange.bind(this)}>
                            { PLATFORM_TEMPLATE_LIST.filter(template => template.id !==platformId).map(platform => (
                                <Radio value={platform.id}>{ platform.name }</Radio>
                            )) }
                        </Radio.Group>
                    </Col>
                </Row>
            ),
            onOk: this.copyTemplateAction.bind(this)
        })
    }

    copyTemplateAction () {
        const { platformId } = getHistoryMatchParams(this.props)
        const { copyPlatformId } = this.state
        if (!copyPlatformId) {
            notify('请选择需要复制的模版')
        }
        this.props.getShoppingMallDesignInfo({
            sourceType: copyPlatformId
        }, res => {
            this.props.editShoppingMallDesignInfo({
                sourceType: platformId,
                decorationInfo: res.decoration_info,
                prodIds: res.prod_ids
            }, () => {
                this.getDesignInfo()
            })
        })
    }

    render () {
        const { children, userInfoInStore } = this.props
        const { decorationInfo } = this.state
        const { platformId } = getHistoryMatchParams(this.props)
        const pStoreId = getBilinInfo('storeId') || 0
        const { biz_type: bizType } = userInfoInStore
        let subNav = []
        if (pStoreId && bizType === 'agent') {
            subNav = ['home', 'special', 'cart', 'owner']
        } else if (pStoreId) {
            subNav = ['special']
        } else {
            subNav = ['global', 'start-page', 'tabbar', 'home', 'special', 'cart', 'owner']
        }

        return (
            <div className="bilin-web shopping-mall-design-detail-page">
                <PageBackHeader
                    title="退出编辑"
                    backUrl={["/shopping-mall/design", `/third-party/${PLATFORM_KEY[platformId]}/release`]}
                    beforeGoBack={this.beforeGoBack.bind(this)}
                    rightCustomizeInfo={(
                        <div className="flex-vertical-center">
                            <Button type="primary" className="button-large mgr-12" ghost onClick={this.copyTemplate.bind(this)}>复制模版</Button>
                            <Button type="primary" className="button-large mgr-12" onClick={this.handleSubmit.bind(this)}>保存并发布</Button>
                        </div>
                    )}
                />
                <PageSubNav
                    navInfoList={subNav.map(nav => ({
                        path: `shopping-mall/design/${platformId}/detail/${nav}`,
                        name: TEMPLATE_MODULE_NAME[nav],
                    }))}
                />
                { decorationInfo ? (
                    <div className="bilin-web-right sub">
                        <DesignTemplateContext.Provider value={{
                            templateInfo: {
                                ...decorationInfo
                            },
                            platformId,
                            subNav,
                            pStoreId,
                            bizType,
                            getHomeUniqueId: this.getHomeUniqueId.bind(this),
                            onChange: this.handleDesignInfoChange.bind(this)
                        }}>
                            { children }
                        </DesignTemplateContext.Provider>
                    </div>
                ) : null }
            </div>
        )
    }
}

export default ShoppingMallDesignDetailPage